package com.settlement.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.settlement.system.common.base.IBaseEnum;
import com.settlement.system.common.constant.SystemConstants;
import com.settlement.system.common.enums.BillCheckStatusEnum;
import com.settlement.system.common.util.StringUtils;
import com.settlement.system.mapper.SysColumnMatchConditionMapper;
import com.settlement.system.model.entity.SysColumnMatch;
import com.settlement.system.mapper.SysColumnMatchMapper;
import com.settlement.system.model.entity.SysColumnMatchCondition;
import com.settlement.system.model.form.ColumnMatchConditionForm;
import com.settlement.system.model.form.ColumnMatchForm;
import com.settlement.system.model.vo.BillProjectConfigImportVo;
import com.settlement.system.model.vo.TmBillConfigConditionImportVo;
import com.settlement.system.service.SnowflakeIdWorker;
import com.settlement.system.service.SysColumnMatchService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * <p>
 * 字段对应关系 服务实现类
 * </p>
 *
 * @author huangrensen
 * @since 2023-09-19
 */
@Service
@RequiredArgsConstructor
public class SysColumnMatchServiceImpl extends ServiceImpl<SysColumnMatchMapper, SysColumnMatch> implements SysColumnMatchService {

    private final SysColumnMatchConditionMapper sysColumnMatchConditionMapper;

    private final RedisTemplate redisTemplate;

    private final SnowflakeIdWorker snowflakeIdWorker = SnowflakeIdWorker.getInstance();
    @Override
    @SuppressWarnings("unchecked")
    public String saveForm(ColumnMatchForm columnMatchForm) {
        SysColumnMatch sysColumnMatch;
        boolean needCreate = false;
        if(StringUtils.hasText(columnMatchForm.getId())){
            sysColumnMatch = this.getById(columnMatchForm.getId());
        }else{
            sysColumnMatch = new SysColumnMatch();
            needCreate = true;
            sysColumnMatch.setId(snowflakeIdWorker.nextId("BCM"));
        }
        BeanUtil.copyProperties(columnMatchForm, sysColumnMatch);
        // 删除旧的符合条件
        sysColumnMatchConditionMapper.delete(new LambdaQueryWrapper<SysColumnMatchCondition>().eq(SysColumnMatchCondition::getMatchId, columnMatchForm.getId()));
        // 新增新的符合条件
        for (ColumnMatchConditionForm columnMatchConditionForm : columnMatchForm.getConditionFormList()) {
            SysColumnMatchCondition condition = new SysColumnMatchCondition();
            BeanUtil.copyProperties(columnMatchConditionForm, condition, "id");
            condition.setMatchId(columnMatchForm.getId());
            sysColumnMatchConditionMapper.insertData(condition);
        }
        // 保存或者更新
        if(needCreate){
            this.baseMapper.insertData(sysColumnMatch);
        }else{
            this.baseMapper.update(sysColumnMatch);
        }
        // 删除缓存
        redisTemplate.delete(SystemConstants.BILL_COLUMN_CONFIG_PREFIX+sysColumnMatch.getPlatformKey());
        if (columnMatchForm.getConditionFormList().size() > 0) {
            redisTemplate.delete(SystemConstants.BILL_COLUMN_CONDITION_PREFIX.formatted(columnMatchForm.getId()));
        }
        return sysColumnMatch.getId();
    }

    @Override
    @SuppressWarnings("unchecked")
    public List<SysColumnMatch> getByPlatform(String platformKey) {
        // 先从缓存取值
        Object value = redisTemplate.opsForValue().get(SystemConstants.BILL_COLUMN_CONFIG_PREFIX+platformKey);
        if(value != null){
            // 直接返回
            return (List<SysColumnMatch>)value;
        }
        List<SysColumnMatch> list = this.list(new LambdaQueryWrapper<SysColumnMatch>()
                .eq(SysColumnMatch::getPlatformKey, platformKey)
                .orderByDesc(SysColumnMatch::getUpdateTime));
        // 条件
        List<SysColumnMatchCondition> conditions;
        for (SysColumnMatch sysColumnMatch : list) {
            sysColumnMatch.setBillCheckName(IBaseEnum.getLabelByValue(sysColumnMatch.getBillCheck(), BillCheckStatusEnum.class));
            conditions = sysColumnMatchConditionMapper.selectList(new LambdaQueryWrapper<SysColumnMatchCondition>().eq(SysColumnMatchCondition::getMatchId, sysColumnMatch.getId()));
            sysColumnMatch.setConditionList(conditions);
        }
        // 加入缓存
        redisTemplate.opsForValue().set(SystemConstants.BILL_COLUMN_CONFIG_PREFIX+platformKey, list, 1, TimeUnit.HOURS);
        return list;
    }

    @Override
    @SuppressWarnings("unchecked")
    public boolean deleteMatch(String idsStr) {
        Assert.isTrue(StrUtil.isNotBlank(idsStr), "删除的数据为空");
        List<Long> ids = Arrays.stream(idsStr.split(",")).map(Long::parseLong).collect(Collectors.toList());
        List<SysColumnMatch> list = this.list(new LambdaQueryWrapper<SysColumnMatch>()
                .in(SysColumnMatch::getId, ids));
        for (SysColumnMatch sysColumnMatch : list) {
            // 删除缓存
            redisTemplate.delete(SystemConstants.BILL_COLUMN_CONFIG_PREFIX+sysColumnMatch.getPlatformKey());
        }
        return this.removeByIds(ids);
    }

    @Override
    public void saveConfig(List<BillProjectConfigImportVo> vos, List<TmBillConfigConditionImportVo> conditionImportVos, String platformKey) {
        // 删除缓存
        redisTemplate.delete(SystemConstants.BILL_COLUMN_CONFIG_PREFIX+platformKey);
        // 删除旧的历史数据
        this.remove(new LambdaQueryWrapper<SysColumnMatch>().eq(SysColumnMatch::getPlatformKey, platformKey));
        vos.removeIf(item -> !StringUtils.hasText(item.getBillType()));
        // 处理条件
        List<TmBillConfigConditionImportVo> importVoList;
        for (BillProjectConfigImportVo vo : vos) {
            importVoList = conditionImportVos.stream().filter(item -> item.getConfigId().equals(vo.getConfigId())).toList();
            vo.setConditionImportVos(importVoList);
        }
        // 保存
        SysColumnMatch sysColumnMatch;
        SysColumnMatchCondition sysColumnMatchCondition;
        List<SysColumnMatchCondition> saveList = new ArrayList<>();
        for (BillProjectConfigImportVo vo : vos) {
            sysColumnMatch = new SysColumnMatch();
            BeanUtils.copyProperties(vo, sysColumnMatch, "billCheck");
            sysColumnMatch.setId(snowflakeIdWorker.nextId("BCM"));
            sysColumnMatch.setPlatformKey(platformKey);
            if(StringUtils.hasText(vo.getBillCheckName()) && vo.getBillCheckName().contains(BillCheckStatusEnum.CHECK.getLabel())){
                sysColumnMatch.setBillCheck(BillCheckStatusEnum.CHECK.getValue());
            }
            if(Objects.isNull(sysColumnMatch.getBillCheck())){
                sysColumnMatch.setBillCheck(BillCheckStatusEnum.TRANSFER.getValue());
            }
            this.baseMapper.insertData(sysColumnMatch);
            // 保存条件
            if(vo.getConditionImportVos() != null && vo.getConditionImportVos().size() > 0){
                for (TmBillConfigConditionImportVo conditionImportVo : vo.getConditionImportVos()) {
                    sysColumnMatchCondition = new SysColumnMatchCondition();
                    BeanUtils.copyProperties(conditionImportVo, sysColumnMatchCondition);
                    sysColumnMatchCondition.setMatchId(sysColumnMatch.getId());
                    saveList.add(sysColumnMatchCondition);
                }
            }
        }
        if(saveList .size() > 0){
            saveList.forEach(sysColumnMatchConditionMapper::insertData);
        }
    }
}
